package com.hjy.search.service.impl;

import cn.hutool.json.JSONUtil;
import com.hjy.common.to.es.SkuEsModel;
import com.hjy.search.constant.EsConstant;
import com.hjy.search.service.ElasticSearchService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean saveSkuProducts(List<SkuEsModel> list) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();
        list.forEach(skuEsModel -> {
            // 设置 indices
            IndexRequest indexRequest = new IndexRequest().index(EsConstant.PRODUCT_INDEX);
            // 设置id
            indexRequest.id(skuEsModel.getSkuId().toString());
            // 设置请求体
            indexRequest.source(JSONUtil.toJsonStr(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return responses.hasFailures();
    }
}
